' Possible return codes
Const ERROR_INSTALL_FAILURE = 1603 
Const ERROR_SUCCESS = 0 

Function configureMySQL ()
   Dim oView, oResult, sTMP, sSQLScript, aQueries
   Dim sDBHost, sDBPort, sDBUsername, sDBPassword, sPortAddon, sConnectionString, oDB, sDBClient, sDBDatabase, sDBUserUsername, sDBUserPassword, sSQL
   Dim aSetupQueryTMP(4), aSetupQuery, aRollbackQuery(3), iCount, iCountRollback, sTMPQuery
   Dim aVariablesToParse, iCountVariables
   
   On Error Resume next
   
   ' Variables to take from WIX and write to php files
   aVariablesToParse = array("WEBSITEIP", "WEBSITEPORT", "WEBSITEDESCRIPTION", "WEBSITEHOSTHEADER", "TARGETDIR", "VIRTUALDIRECTORYNAME", "SQLDATABASE", "DBHOST", "SQLUSERUSERNAME", "SQLUSERPASSWORD", "USERUSERNAME", "USERPASSWORD", "USERMD5PASSWORD", "USEREMAIL", "LOCALURL", "FIRSTIP", "DBPORT", "DBCLIENT", "URLHOST", "URLDIR")
  
   
   ' Get SQLScript from WIX
   Set oView = Session.Database.OpenView("SELECT Data FROM Binary WHERE Name='SQLScript'")
   oView.Execute()
   Set oResult = oView.Fetch
   Do
     sTMP = oResult.ReadStream(1,10,1)
     sSQLScript = sSQLScript & sTMP
     If Len(sTMP) < 10 Then exit do
   Loop
  
   ' Open database connection
   
   ' Get values from WIX
   sDBHost              = Session.Property("DBHOST")
   sDBPort              = Session.Property("DBPORT")
   sDBUsername          = Session.Property("SQLADMINUSERNAME")
   sDBPassword          = Session.Property("SQLADMINPASSWORD")
   sDBClient            = Session.Property("DBCLIENT")
   sDBDatabase          = Session.Property("SQLDATABASE")
   sDBUserUsername      = Session.Property("SQLUSERUSERNAME")
   sDBUserPassword      = Session.Property("SQLUSERPASSWORD")
   sMYSQLPrivileges     = Session.Property("MYSQLPrivileges")
   
   ' Drop port if localhost is chosen
   'sPortAddon = ":" & sDBPort
   'If sDBHost = "localhost" Then
   '  sPortAddon = ""
   'End if
   
   ' Connectionstring
	'sConnectionString = "driver=MySQL ODBC 3.51 Driver;Server=" & sDBHost & ";Port=" & sDBPort  & ";uid=" & sDBUsername & ";pwd=" & sDBPassword & ";database=mysql"
	sConnectionString = "driver=" & Session.Property("MYSQL_ODBC_DRIVER") & ";Server=" & sDBHost & ";Port=" & sDBPort  & ";uid=" & sDBUsername & ";pwd=" & sDBPassword & ";database=mysql"
		
   ' Crate ADODB Object
   Set oDB = CreateObject("ADODB.Connection")
      
   ' Check if object could be created
   If( Err.Number <> 0 ) Then 
       MsgBox "Unable to create ADODB Object - please verify that ASP.NET 2.0 is installed!" & vbCrLf & _ 
              "Error Details: " & Err.Description & " [Number:" & Hex(Err.Number) & "]", vbCritical, "Error" 
       configureMySQL = ERROR_INSTALL_FAILURE
       Exit Function
   End if 

   ' Open connection
    oDB.Open(sConnectionString)
    	
   ' Check if connection worked
   If( Err.Number <> 0 ) Then 
    	 MsgBox "Unable to connect to Database - Setup failed!" & vbCrLf & _ 
              "Error Details: " & Err.Description & " [Number:" & Hex(Err.Number) & "]", vbCritical, "Error" 
       configureMySQL = ERROR_INSTALL_FAILURE
       Exit Function 
   End If

   ' Create database
   aSetupQueryTMP(0) = "CREATE DATABASE " & sDBDatabase
   aRollbackQuery(0) = "DROP DATABASE " & sDBDatabase & ";"
   
   ' Create user and privileges
   aSetupQueryTMP(1) = "GRANT " & sMYSQLPrivileges & " on " & sDBDatabase & ".* to " & sDBUserUsername & "@'" & sDBClient & "' identified by '" & sDBUserPassword & "'"
   aRollbackQuery(1) = "DROP USER " & sDBUserUsername & "@'" & sDBClient & "';"
   
   ' Flush privileges
   aSetupQueryTMP(2) = "FLUSH PRIVILEGES"
   aRollbackQuery(2) = "FLUSH PRIVILEGES;"
   
   ' Change database
   aSetupQueryTMP(3) = "USE " & sDBDatabase
   
   ' Combine setup queries and setup script
   sSQLScript = join(aSetupQueryTMP, " ;" & vbCrLf) & sSQLScript
   aSetupQuery = split(sSQLScript, ";"& vbCrLf)
   
   ' Execute setup actions
   For iCount = LBound(aSetupQuery) to UBound(aSetupQuery)
     sSQL = aSetupQuery(iCount)
     
     ' Parse query to insert WIX properties
     For iCountVariables = LBound(aVariablesToParse) To UBound(aVariablesToParse)
          If InStr(1, sSQL, "@@" & aVariablesToParse(iCountVariables) & "@@") > 0 Then
   	        sSQL = Replace(sSQL, "@@" & aVariablesToParse(iCountVariables) & "@@", Session.Property(aVariablesToParse(iCountVariables)))
   	      End if
     Next
     
     ' Execute query
     If Len(Trim(sSQL)) > 0 Then
       Set oResultSet = oDB.Execute(sSQL)
     End if

     If( Err.Number <> 0 ) Then 
        sTMPQuery = sSQL
        If Len(sTMPQuery) > 512 Then
          sTMPQuery = Left(sTMPQuery, 512) & "..."
        End if
        
    	  MsgBox "Database setup failed by executing query: " & vbCrLf & vbCrLf & sTMPQuery & vbCrLf & vbCrLf & "Error Details: " & Err.Description & " [Number:" & Hex(Err.Number) & "]" & vbCrLf & vbCrLf & "Click OK to start rollback...", vbCritical, "Error" 
        
        For iCountRollback = LBound(aRollbackQuery) to UBound(aRollbackQuery)
          sSQL = aRollbackQuery(iCountRollback)
          Set oResultSet = oDB.Execute(sSQL)
        Next
        
        configureMySQL = ERROR_INSTALL_FAILURE
        Exit Function 
     End If
   Next
   
   configureMySQL = ERROR_SUCCESS
End Function

